import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

def create_database():
    try:
        # 连接到默认的postgres数据库
        conn = psycopg2.connect(
            dbname="postgres",
            user="postgres",
            password="postgres",
            host="localhost",
            port="5432"
        )
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        
        # 创建游标
        cur = conn.cursor()
        
        # 检查数据库是否存在
        cur.execute("SELECT 1 FROM pg_database WHERE datname = 'dormitory'")
        exists = cur.fetchone()
        
        if not exists:
            # 创建数据库
            cur.execute("CREATE DATABASE dormitory")
            print("数据库 'dormitory' 创建成功！")
        else:
            print("数据库 'dormitory' 已经存在。")
        
        # 关闭连接
        cur.close()
        conn.close()
        
    except Exception as e:
        print(f"创建数据库时出错：{str(e)}")

if __name__ == "__main__":
    create_database() 